package com.ziwei.doushu;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.*;
import androidx.appcompat.app.AppCompatActivity;
import com.ziwei.doushu.model.BirthInfo;
import com.ziwei.doushu.core.ZiweiCalculator;

/**
 * 输入界面Activity
 */
public class InputActivity extends AppCompatActivity {
    
    private EditText etBirthYear;
    private EditText etBirthMonth;
    private EditText etBirthDay;
    private Spinner spinnerHour;
    private RadioGroup rgGender;
    private RadioButton rbMale;
    private RadioButton rbFemale;
    private Button btnCalculate;
    
    private ZiweiCalculator calculator;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_input);
        
        initViews();
        setupSpinner();
        setListeners();
        
        calculator = new ZiweiCalculator();
    }
    
    private void initViews() {
        etBirthYear = findViewById(R.id.et_birth_year);
        etBirthMonth = findViewById(R.id.et_birth_month);
        etBirthDay = findViewById(R.id.et_birth_day);
        spinnerHour = findViewById(R.id.spinner_hour);
        rgGender = findViewById(R.id.rg_gender);
        rbMale = findViewById(R.id.rb_male);
        rbFemale = findViewById(R.id.rb_female);
        btnCalculate = findViewById(R.id.btn_calculate);
    }
    
    private void setupSpinner() {
        // 设置时辰选项
        String[] hours = {
            "子时(23-1点)", "丑时(1-3点)", "寅时(3-5点)", "卯时(5-7点)",
            "辰时(7-9点)", "巳时(9-11点)", "午时(11-13点)", "未时(13-15点)",
            "申时(15-17点)", "酉时(17-19点)", "戌时(19-21点)", "亥时(21-23点)"
        };
        
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, 
            android.R.layout.simple_spinner_item, hours);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerHour.setAdapter(adapter);
        
        // 默认选择子时
        spinnerHour.setSelection(0);
    }
    
    private void setListeners() {
        btnCalculate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (validateInput()) {
                    calculateAndShowResult();
                }
            }
        });
    }
    
    private boolean validateInput() {
        String yearStr = etBirthYear.getText().toString().trim();
        String monthStr = etBirthMonth.getText().toString().trim();
        String dayStr = etBirthDay.getText().toString().trim();
        
        if (yearStr.isEmpty() || monthStr.isEmpty() || dayStr.isEmpty()) {
            showError("请填写完整的出生信息");
            return false;
        }
        
        try {
            int year = Integer.parseInt(yearStr);
            int month = Integer.parseInt(monthStr);
            int day = Integer.parseInt(dayStr);
            
            if (year < 1900 || year > 2100) {
                showError("出生年份应在1900-2100之间");
                return false;
            }
            
            if (month < 1 || month > 12) {
                showError("出生月份应在1-12之间");
                return false;
            }
            
            if (day < 1 || day > 31) {
                showError("出生日期应在1-31之间");
                return false;
            }
            
            // 简单的日期验证
            if (month == 2 && day > 29) {
                showError("2月最多29天");
                return false;
            }
            
            if ((month == 4 || month == 6 || month == 9 || month == 11) && day > 30) {
                showError("该月最多30天");
                return false;
            }
            
        } catch (NumberFormatException e) {
            showError("请输入有效的数字");
            return false;
        }
        
        if (rgGender.getCheckedRadioButtonId() == -1) {
            showError("请选择性别");
            return false;
        }
        
        return true;
    }
    
    private void calculateAndShowResult() {
        try {
            // 显示计算中提示
            btnCalculate.setText("计算中...");
            btnCalculate.setEnabled(false);
            
            // 获取输入信息
            BirthInfo birthInfo = getBirthInfo();
            
            // 在后台线程进行计算
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        // 模拟计算时间
                        Thread.sleep(1000);
                        
                        // 计算紫微斗数
                        com.ziwei.doushu.model.ZiweiResult result = calculator.calculate(birthInfo);
                        
                        // 切换到主线程显示结果
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                showResult(result);
                            }
                        });
                        
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
            
        } catch (Exception e) {
            showError("计算过程中出现错误：" + e.getMessage());
            btnCalculate.setText("计算排盘");
            btnCalculate.setEnabled(true);
        }
    }
    
    private BirthInfo getBirthInfo() {
        int year = Integer.parseInt(etBirthYear.getText().toString().trim());
        int month = Integer.parseInt(etBirthMonth.getText().toString().trim());
        int day = Integer.parseInt(etBirthDay.getText().toString().trim());
        int hour = spinnerHour.getSelectedItemPosition();
        boolean isMale = rbMale.isChecked();
        
        return new BirthInfo(year, month, day, hour, isMale);
    }
    
    private void showResult(com.ziwei.doushu.model.ZiweiResult result) {
        // 恢复按钮状态
        btnCalculate.setText("计算排盘");
        btnCalculate.setEnabled(true);
        
        // 跳转到结果界面
        Intent intent = new Intent(InputActivity.this, ResultActivity.class);
        intent.putExtra("result", result);
        startActivity(intent);
    }
    
    private void showError(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }
}
